package
{
	import flash.display.BlendMode;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.Event;
	
	import com.kairos.engine.RTAnimation;
	import com.kairos.engine.RTObject;
	import com.kairos.motion.MovieClipRT;	

	public class ParticleRT extends RTObject implements RTAnimation
	{
		private var _parent : DisplayObjectContainer;
		private var _mcSprite : MovieClip;
		private var _oSpriteAnimation : MovieClipRT;
		
		private var _x : Number;
		private var _y : Number;
		private var _speedX : Number;
		private var _speedY : Number;
		private var _life : Number;
		private var _maxLife : Number;
		private var _onDeath : Function;
		
		private static const GRAVITY : Number = 98;
		private static const FRICTION : Number = .995;
		
		[Embed(source="../lib/example-lib.swf", symbol="ParticleAnimation")]
			private var ParticleAnimation : Class;
		
		public function ParticleRT ( parent:DisplayObjectContainer, x:Number=0, y:Number=0, speedX:Number=0, speedY:Number=0, maxLife:Number=0, scale:Number=1, onDeath:Function=null )
		{
			_parent = parent;
			
			_mcSprite = new ParticleAnimation() as MovieClip;
			_mcSprite.scaleX = _mcSprite.scaleY = scale;
			_mcSprite.x = x;
			_mcSprite.y = y;
			_mcSprite.blendMode = BlendMode.ADD;
			_mcSprite.rotation = Math.floor( Math.random() * 360 ) ;
			
			_parent.addChild( _mcSprite );
			
			_oSpriteAnimation = new MovieClipRT ( _mcSprite, 24 );
			
			_x = x;
			_y = y;
			_speedX = speedX;
			_speedY = speedY;
			_life = 0;
			_maxLife = maxLife;
			_onDeath = onDeath;
		}
		public override	function onTick(e:Event=null):void
		{
			var stepInSeconds : Number = getLocalStepInSecond( e );
			var step : Number = getLocalStep( e );
			
			_speedX = _speedX * FRICTION;
			_speedY = ( _speedY + ( GRAVITY * stepInSeconds ) ) * FRICTION;
			
			_x += _speedX * stepInSeconds;
			_y += _speedY * stepInSeconds;
			
			_collide();
			
			_life += step;
			
			_mcSprite.x = _x;
			_mcSprite.y = _y;
			
			if( _life > _maxLife )
			{
				_onDeath.call( null, this );
				_parent.removeChild( _mcSprite );
			}
		}
		
		private function _collide():void
		{
			if( _x > 500 )
			{
				_x = 500;
				_speedX *= -.5
			}
			if( _y > 130 )
			{
				_y = 130;
				_speedY *= -.5
			}
		}
		
		public override function start():void
		{
			super.start();
			_oSpriteAnimation.start();
		}
		
		public override function stop():void
		{
			super.stop();
			_oSpriteAnimation.stop();
		}
		
		public function getView () : MovieClip
		{
			return _mcSprite;
		}
	}
}